<template>
  <div class="warp-main">
    <div class="warp-left">
      <div class="search">
        <el-input
          class="search-input"
          v-model="keywords"
          clearable
          placeholder="请输入标题关键字"
          @input="inputChange"
        />
      </div>
      <div class="list">
        <el-scrollbar ref="scrollbarRef" height="690px" always @scroll="scroll">
          <div class="knowledge-container" ref="innerRef">
            <div :class="knowledg.knowledgeId == knowledgeSelected.knowledgeId? 'knowledge knowledge-selected' : 'knowledge'" v-for="knowledg in knowledges" :key="knowledg.knowledgeId" @click="clickKnowledge(knowledg)">
              <div class="knowledge-top">
                <span class="title">{{knowledg.title}}</span>
              </div>
              <div class="knowledge-buttom">
                <div class="knowledge-buttom-item">
                  <el-icon class="knowledge-buttom-item-icon" size="15"><Timer /></el-icon>
                  <span>{{knowledg.createTime}}</span>
                </div>
                <div class="knowledge-buttom-item">
                  <el-icon class="knowledge-buttom-item-icon" size="15"><View /></el-icon>
                  <span>{{knowledg.viewNum}}</span>
                </div>
                <div class="knowledge-buttom-item">
                  <span class="knowledge-buttom-item-icon">版本:</span>
                  <span>{{knowledg.version}}</span>
                </div>
                <div class="knowledge-buttom-item">
                  <span>{{knowledg.createBy}}</span>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
        <div v-loading="loading"></div>
      </div>
    </div>
    <div class="warp-right">
      <div class="operation">
        <div class="create-button">
          <span class="edit-button operation-item" @click="showEditor">新建文档</span>
        </div>
        <div>
          <span class="edit-button operation-item" @click="editKnowledge">编辑</span>
          <span class="delete-button operation-item" @click="deleteKnowledge">删除</span>
        </div>
      </div>
      <!--仅浏览器-->
      <MdPreview class="my-preview" :editorId="mdPriviewId" :modelValue="form.content" :scrollElement="scrollElement" :showCodeRowNumber="true"/>
    </div>
    <el-drawer v-model="visible" :show-close="false" :close-on-click-modal="false" size="90%" :before-close="handleClose" @open="openDrawer">
      <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">新建知识库</h4>
        <el-button type="danger" @click="cancelKnowledge">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="submitKnowledge">
          <el-icon class="el-icon--left"><Check /></el-icon>
          提交
        </el-button>
      </template>
      <el-form :model="form">
        <el-form-item label="标题">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
      </el-form>
      <MdEditor class="my-editor" v-model="form.content" @onSave="onSave" @onUploadImg="onUploadImg" :toolbars="toolbars">
        <template #defToolbars>
          <ExportPDF :fileName="form.title" :modelValue="form.content" />
        </template>
      </MdEditor>
    </el-drawer>
    <!--编辑器+浏览器-->

  </div>
</template>
<script lang="ts" setup>
  import {reactive, ref, onMounted} from "vue"
  import {Edit, Share, Delete, Search, Upload} from '@element-plus/icons-vue'
  import to from "@/utils/to";
  import {ElMessage, ElMessageBox, ElNotification,} from "element-plus";
  import axios from 'axios'

  import {
    knowledgeList,
    getKnowledge,
    insert,
    updateKnowledge,
    del
  } from "@/api/knowledge/knowledge";

  import { MdEditor, MdPreview } from 'md-editor-v3';
  import { ExportPDF } from '@vavt/v3-extension';
  import '@vavt/v3-extension/lib/asset/ExportPDF.css';
  import 'md-editor-v3/lib/style.css';
  import {getToken} from '@/utils/auth';
  const prefix = import.meta.env.VITE_APP_BASE_API

  const toolbars = [
      'bold',
      'underline',
      'italic',
      '-',
      'strikeThrough',
      'title',
      'sub',
      'sup',
      'quote',
      'unorderedList',
      'orderedList',
      'task', // ^2.4.0
      '-',
      'codeRow',
      'code',
      'link',
      'image',
      'table',
      'mermaid',
      'katex',
      '-',
      'revoke',
      'next',
      'save',
      '0',
      '=',
      'pageFullscreen',
      'fullscreen',
      'preview',
      'htmlPreview',
      'catalog',
    ];

  const authorizeHeader = reactive({})
  const pageNum = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const keywords = ref('');

  const scrollElement = document.documentElement;
  const mdPriviewId = ref('mdPriviewId');
  const knowledgeSelected = ref({
    knowledgeId: null,
    title: '',
    content: '',
    version: null,
    viewNum: null,
  });

  const max = ref(0)
  const value = ref(0)
  const toButtom = ref(410)
  const innerRef = ref<HTMLDivElement>()
  const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()
  const loading = ref(false)
  const visible = ref(false)
  const form = reactive({
    knowledgeId: null,
    title: '',
    content: '',
    version: null,
    viewNum: null,
  })

  const knowledges = ref([])
  const {proxy} = getCurrentInstance()
  const {sys_normal_disable, sys_user_sex} = proxy.useDict(
    'sys_normal_disable'
  )

  const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          console.log('onUploadImg prefix:', prefix + '/file/upload')
          const form = new FormData();
          form.append('file', file);
          axios
            .post(prefix + '/file/upload', form, {
              headers: {
                'Content-Type': 'multipart/form-data',
                Authorization: 'Bearer ' + getToken()
              }
            })
            .then((res) => rev(res))
            .catch((error) => rej(error));
        });
      })
    );

    // 方式一
    callback(res.map((item) => 'http://' + window.location.host + ':10002'+ item.data.data.url));
    console.log('onUploadImg res:', res)

    // 方式二
    // callback(
    //   res.map((item) => ({
    //     url: 'http://10.10.55.4:22:10002' + item.data.data.url,
    //     alt: 'alt',
    //     title: 'title'
    //   }))
    // );
  };

  const save = async (form) =>{
    let title = form.title
    if(!title){
      ElMessage.warning('标题不能为空！');
      return
    }
    let knowledgeId = form.knowledgeId
    //更新
    if(knowledgeId){
      const [err, res] = await to(updateKnowledge(form))
      if (res) {
        console.log('update:', res)
        visible.value = false
      }
    }else{
      const [err, res] = await to(insert(form))
      if (res) {
        console.log('insert:', res)
        visible.value = false
      }
    }
    let params = {
      pageNum: 1,
      pageSize: pageSize.value,
    }
    search(params);
  }
  const onSave = async ()=>{
    console.log('onSave:', form)
    save(form);
  }

  const submitKnowledge = async () =>{
    console.log('submitKnowledge:', form)
    save(form);
  }

  const clickKnowledge = async (knowledge)=> {
    let id = knowledge.knowledgeId;
    const [err, res] = await to(getKnowledge(id))
    if (res) {
      knowledge = res.data
      knowledgeSelected.value = knowledge
      form.knowledgeId = knowledge.knowledgeId
      form.title = knowledge.title
      form.content = knowledge.content
      form.viewNum = knowledge.viewNum
      form.version = knowledge.version
    }
  }

  const inputChange = (knowledge)=>{
    console.log('keyword:', keywords.value);
    let params = {
      title: keywords.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    search(params);
  }
  const scroll = (scrollTop)=>{
    value.value = scrollTop

    console.log('max:', max.value, 'scrollTop:', scrollTop.scrollTop)
    let too = max.value - scrollTop.scrollTop

    if(too <= toButtom.value && !loading.value){
      let pageNum = pageNum.value + 1;
      let sum = pageNum * pageSize.value;
      if(sum >= total.value){
        return
      }
      loading.value = true
      console.log('search...')
      let params = {
        title: keywords.value,
        pageNum: pageNum,
        pageSize: pageSize.value,
      }
      search(params);
    }
  }
  const showEditor = (knowledge)=>{
    visible.value = true
    knowledgeSelected.value = {}
  }

  const handleClose = () => {
    ElMessageBox.confirm('是否要放弃本次修改?')
      .then(() => {
        visible.value = false
      })
      .catch(() => {

      })
  }

  const editKnowledge = () =>{
    let id = knowledgeSelected.value.knowledgeId;
    if(!id){
      ElMessage.warning('请先选择一条数据！');
      return
    }
    visible.value = true
  }
  const openDrawer = () => {
    console.log('openDraw:', knowledgeSelected.value)

    form.knowledgeId = knowledgeSelected.value.knowledgeId
    form.title = knowledgeSelected.value.title
    form.content = knowledgeSelected.value.content
  }

  const deleteKnowledge = async () => {
    console.log('knowledgeSelected:', knowledgeSelected)
    let id = knowledgeSelected.value.knowledgeId;
    if (!id) {
      ElMessage.warning('请先选择一条数据！');
      return
    }
    const result = await ElMessageBox.confirm('请确认提交吗?', {
      title: '提示',
      type: 'warning',
    }).then(() => {
      return true;
    }).catch(() => {
      return false;
    });

    console.log(result);
    if (result) {
      const [err, res] = await to(del(id))
      if (res) {
        console.log('deleteKnowledge:', res)
      }
      knowledgeSelected.value = {}
      form.content = null;
      //查询知识库数据
      let params = {
        title: '',
        pageNum: 1,
        pageSize: pageSize.value,
      }
      search(params);
    }
  }
  const cancelKnowledge = () =>{
    handleClose();
  }


  const search = async (params) =>{
    const [err, res] = await to(knowledgeList(params))
    if (res) {
      console.log('search:', res)
      knowledges.value =  res.rows
      total.value = res.total

    }
  }

  onMounted(() => {
    console.log('onMounted...')
    authorizeHeader.value = {
      Authorization: 'Bearer ' + getToken()
    }
    console.log('authorizeHeader:', authorizeHeader.value)
    //查询知识库数据
    let params = {
      title: keywords.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    search(params);
    //设置知识库列表滚动条滚动到底部380的时候触发相关逻辑
    max.value = innerRef.value!.clientHeight - toButtom.value

  })

  onUnmounted(() => {
    console.log('onUnmounted...')
  })


</script>
<style>
  .warp-main {
    height: 98%;
    background-color: white;
    padding: 10px;
    margin: 5px 10px;

    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

  }
  .warp-left{
    width: 35%;
    height: 100%;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

  }
  .search-input{
    width: 300px;
    height: 40px;
    margin: 5px;
  }
  .list{
    height: 90%;
    width: 100%;
  }
  .knowledge-container{
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
  }
  .knowledge{
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    margin: 5px;
    padding: 5px;
    width: 100%;
    background-color: #f5f5f5;
    border-radius: 10px;
    height: auto;
    cursor: pointer;
  }
  .knowledge-selected{
    border: 1px solid #409eff;
  }
  .knowledge-top{
    width: 100%;
    text-align: left;
    font-size: 18px;
    font-weight: bold;
    padding: 10px;
    margin-bottom: 5px;

  }
  .knowledge-buttom{
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 5px;
  }
  .knowledge-buttom-item{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .knowledge-buttom-item-icon{
    margin-right: 5px;
  }
  .warp-right{
    width: 65%;
    height: 90%;
    margin-left: 10px;
  }
  .operation{
    width: 100%;
    text-align: right;
    padding-right: 30px;
    font-size: 14px;

    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    padding: 8px;

  }
  .operation-item{
    margin: 5px;
    cursor: pointer;
  }
  .edit-button{
    color: #409eff;
  }
  .delete-button{
    color: red;
  }
  .create-button{
    width: auto;
  }
  .my-preview{
    height: 680px;
    border: 1px dashed #409eff;
  }
  .my-editor{
    height: 680px;
  }
</style>
